package com.yvon.maple.service.auth.valicode.validate.code.generator;

import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.yvon.boot.common.result.GlobalException;
import com.yvon.maple.service.auth.param.CodeParam;
import com.yvon.maple.service.auth.service.SecurityUserService;
import com.yvon.maple.service.auth.valicode.validate.code.properties.CodeProperties;
import com.yvon.maple.service.auth.valicode.validate.code.repository.CodeRepository;
import com.yvon.maple.service.auth.valicode.vo.CodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * 短信验证码生成器
 * @author Aijm
 * @since 2019/5/26
 */
@Component(SmsCodeGenerator.GENERATOR)
public class SmsCodeGenerator implements CodeGenerator {

	public static final String GENERATOR = "smsCodeGenerator";

	@Autowired
	private CodeProperties codeProperties;

	@Autowired
	private CodeRepository codeRepository;

	@Autowired
	private SecurityUserService securityUserService;

	/**
	 * 生成短信的验证码
	 *
	 * @return {@link CodeVo }
	 * @author : Yvon / 2021-08-24
	 */
	@Override
	public CodeVo generate(CodeParam param) {
		Assert.isTrue(ReUtil.contains(RegexPool.MOBILE, param.getKey()), "手机号码格式有误");
		CodeVo codeVo = codeRepository.get(param.getValidateType(), param.getKey());
		if (Objects.nonNull(codeVo) && !codeVo.isExpire()) {
			throw new GlobalException("请勿频繁发送短信");
		}
		securityUserService.loadUserByMobile(param.getKey());
		String code = RandomUtil.randomNumbers(codeProperties.getSms().getLength());
		return new CodeVo(code, codeProperties.getSms().getExpire(), param.getKey());
	}
}